package com.jy.appmarket.screenlock.service;

import java.util.List;

import android.Manifest.permission;
import android.app.ActivityManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.support.v4.content.LocalBroadcastManager;
import android.telephony.TelephonyManager;

import com.jy.appmarket.screenlock.LockScreenManager;
import com.jy.appmarket.screenlock.prefs.LockPrefs;
import com.jy.appmarket.screenlock.prefs.LockPrefs.PasswordType;
import com.jy.appmarket.screenlock.receiver.KeyEventReceiver;

import com.jy.appmarket.utils.LogUtil;

/**
 * 类说明：
 * 
 * @author kalui.huang
 * @date 2015-1-21
 * @version 1.0
 */
public class LockerService extends Service {
	private static final String TAG = "LockerService";
	private static boolean isComingCall = false;
	private static boolean isCalling = false;
	private CountDownTimer mDelayTimer = null;
	public static final int NET_TAG_PHRASE = 3;
	public static final int NET_TAG_WALLPAPER = 4;

	public static final String TOOLBOX_RECIVE_SMS_ACTION = "recive_sms_content_action";
	public static final String SMS_WATCHER_UNREAD_COUNT = "sms_watcher_unread_count";
	public static final String SMS_WATCHER_DATE = "sms_watcher_date";
	public static final String SMS_WATCHER_ADDRESS = "sms_watcher_address";
	public static final String TOOLBOX_RECIVE_CALL_ACTION = "recive_call_content_action";
	public static final String CALL_WATCHER_UNREAD_COUNT = "call_watcher_unread_count";
	public static final String CALL_WATCHER_DATE = "call_watcher_date";
	private SMSContentObserver mSmsObserver = null;

	private KeyEventReceiver mKeyEventReceiver;

	public static boolean isCalling() {
		return isCalling;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	public static void startService(Context context) {
		Intent intent = new Intent(context, LockerService.class);
		context.startService(intent);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		LogUtil.i("LockerService", "onCreate");
		IntentFilter filter = new IntentFilter();
		filter.setPriority(1000);
		filter.addAction(Intent.ACTION_SCREEN_OFF);
		filter.addAction(Intent.ACTION_SCREEN_ON);

		initReciverAction();
		IntentFilter filterAlarm = new IntentFilter();
		for (int j = 0; j < alarmRingActions.length; j++) {
			filterAlarm.addAction(alarmRingActions[j]);
		}
		for (int i = 0; i < alarmDoneActions.length; i++) {
			filterAlarm.addAction(alarmDoneActions[i]);
		}
		registerReceiver(mAlarmReceiver, filterAlarm);
		registerReceiver(mReceiver, filter);

		mKeyEventReceiver = new KeyEventReceiver();
		registerReceiver(mKeyEventReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

		registerReceiver(mCallReceiver, new IntentFilter(
				TelephonyManager.ACTION_PHONE_STATE_CHANGED));
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (mSmsObserver == null) {
			mSmsObserver = new SMSContentObserver(this, new Handler());
			Uri uri = Uri.parse("content://sms");
			ContentResolver resolver = this.getContentResolver();
			resolver.registerContentObserver(uri, true, mSmsObserver);
		}
		return START_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		unregisterReceiver(mReceiver);
		unregisterReceiver(mAlarmReceiver);
		unregisterReceiver(mKeyEventReceiver);
		unregisterReceiver(mCallReceiver);
		if (mSmsObserver != null) {
			ContentResolver resolver = this.getContentResolver();
			resolver.unregisterContentObserver(mSmsObserver);
			mSmsObserver = null;
		}
		startService(this);
	}

	public static void stopService(Context context) {
		Intent intent = new Intent(context, LockerService.class);
		context.stopService(intent);
	}

	public static boolean isServiceRunning(Context context) {
		boolean isRunning = false;
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> serviceList = activityManager
				.getRunningServices(50);
		if (serviceList.size() == 0) {
			return false;
		}
		for (int i = 0; i < serviceList.size(); i++) {
			if (serviceList.get(i).service.getClassName().equals(LockerService.class.getName()) == true
					&& serviceList.get(i).service.getPackageName().equals(context.getPackageName())) {
				isRunning = true;
				break;
			}
		}
		return isRunning;
	}

	private static int lastetState = TelephonyManager.CALL_STATE_IDLE; // 最后的状态

	private BroadcastReceiver mCallReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
				// 修复bug，未开启锁屏时，接电话后锁屏开启
				if (LockPrefs.getStartLocker(context)) {
					TelephonyManager tm = (TelephonyManager) context
							.getSystemService(Service.TELEPHONY_SERVICE);
					onPhoneStateChanged(tm.getCallState(), intent.getStringExtra("incoming_number"));
				}
			}
		}
	};

	private void onPhoneStateChanged(int state, String incomingNumber) {
		try {
			switch (state) {
			case TelephonyManager.CALL_STATE_IDLE: // 当前电话处于闲置状态
				LogUtil.d(TAG, "当前电话处于闲置状态CALL_STATE_IDLE, isRinging:");
				isCalling = false;
				if (isComingCall) {
					isComingCall = false;
					LockScreenManager.getInstance(LockerService.this).lock();
				}
				break;
			case TelephonyManager.CALL_STATE_RINGING: // 当前电话处于铃响状态
				// 可能连续调用两次
				LogUtil.d(TAG, "CALL_STATE_RINGING电话号码为 " + incomingNumber);
				isCalling = true;
				isComingCall = true;
				LockScreenManager.getInstance(LockerService.this).unLock(true);
				break;
			case TelephonyManager.CALL_STATE_OFFHOOK: // 当前电话处于接听状态
				LogUtil.d(TAG, "当前电话处于通话状态CALL_STATE_OFFHOOK ");
				isCalling = true;
				break;
			}
			// 如果当前状态为空闲,上次状态为响铃中的话,则认为是未接来电
			if (lastetState == TelephonyManager.CALL_STATE_RINGING
					&& state == TelephonyManager.CALL_STATE_IDLE
					&& LockScreenManager.getInstance(LockerService.this).isLocked()) {
				sendSmgWhenMissedCall(incomingNumber);
			}
			lastetState = state;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void sendSmgWhenMissedCall(String incomingNumber) {
		int result = 0;
		long longdate = 0;
		Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI,
				new String[] { Calls.TYPE, Calls.NEW, Calls.DATE }, "type=3 and new=1", null,
				"date desc");

		if (cursor == null) {
			return;
		}
		result = cursor.getCount();
		if (cursor.moveToFirst()) { // 获取最近的一条来电内容
			int dateIndex = cursor.getColumnIndex("date");
			longdate = cursor.getLong(dateIndex);
		}
		// return result;
		if (result > 0) {
			Intent it = new Intent(TOOLBOX_RECIVE_CALL_ACTION);
			it.putExtra(CALL_WATCHER_UNREAD_COUNT, result);
			it.putExtra(CALL_WATCHER_DATE, longdate);
			sendBroadcast(it);
		}
		cursor.close();

	}

	public final BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			LogUtil.d(TAG, "receive broadcast,action=" + action);
			if (action.equals(Intent.ACTION_SCREEN_OFF)) {
				int delayTime = LockPrefs.getDelayTime(LockerService.this).getValue();
				if (LockPrefs.getStartLocker(LockerService.this)) {
					if (LockPrefs.getPasswordType(LockerService.this) == PasswordType.NO_PASSWORD
							|| delayTime <= 0) {
						lock();
					} else {
						mDelayTimer = new CountDownTimer(delayTime * 1000, 1000) {
							@Override
							public void onTick(long millisUntilFinished) {
							}

							@Override
							public void onFinish() {
								lock();
							}
						}.start();
					}
				}
			} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
				if (mDelayTimer != null) {
					mDelayTimer.cancel();
					mDelayTimer = null;
				}
			}
		}
	};

	private String[] alarmRingActions = new String[14];
	private String[] alarmDoneActions = new String[16];

	private void initReciverAction() {
		alarmRingActions[0] = "com.android.deskclock.ALARM_ALERT";
		alarmRingActions[1] = "com.android.alarmclock.ALARM_ALERT";
		alarmRingActions[2] = "com.lge.clock.alarmclock.ALARM_ALERT";
		alarmRingActions[3] = "com.samsung.sec.android.clockpackage.alarm.ALARM_ALERT";
		alarmRingActions[4] = "com.sonyericsson.alarm.ALARM_ALERT";
		alarmRingActions[5] = "com.htc.android.worldclock.ALARM_ALERT";
		alarmRingActions[6] = "com.htc.worldclock.ALARM_ALERT";
		alarmRingActions[7] = "com.lenovomobile.deskclock.ALARM_ALERT";
		alarmRingActions[8] = "com.cn.google.AlertClock.ALARM_ALERT";
		alarmRingActions[9] = "com.htc.android.worldclock.intent.action.ALARM_ALERT";
		alarmRingActions[10] = "com.lenovo.deskclock.ALARM_ALERT";
		alarmRingActions[11] = "com.oppo.alarmclock.alarmclock.ALARM_ALERT";
		alarmRingActions[12] = "com.zdworks.android.zdclock.ACTION_ALARM_ALERT";
		alarmRingActions[13] = "com.dianxinos.clock.ALARM_ALERT";

		alarmDoneActions[0] = "com.android.deskclock.ALARM_DONE";
		alarmDoneActions[1] = "com.android.alarmclock.ALARM_DONE";
		alarmDoneActions[2] = "com.lge.clock.alarmclock.ALARM_DONE";
		alarmDoneActions[3] = "com.samsung.sec.android.clockpackage.alarm.ALARM_DONE";
		alarmDoneActions[4] = "com.sonyericsson.alarm.ALARM_DONE";
		alarmDoneActions[5] = "com.htc.android.worldclock.ALARM_DONE";
		alarmDoneActions[6] = "com.htc.worldclock.ALARM_DONE";
		alarmDoneActions[7] = "com.lenovomobile.deskclock.ALARM_DONE";
		alarmDoneActions[8] = "com.cn.google.AlertClock.ALARM_DONE";
		alarmDoneActions[9] = "com.htc.android.worldclock.intent.action.ALARM_DONE";
		alarmDoneActions[10] = "com.lenovo.deskclock.ALARM_DONE";
		alarmDoneActions[11] = "com.oppo.alarmclock.alarmclock.ALARM_DONE";
		alarmDoneActions[12] = "com.zdworks.android.zdclock.ACTION_ALARM_DONE";
		alarmDoneActions[13] = "com.android.alarmclock.alarm_killed";
		alarmDoneActions[14] = "alarm_killed";
		alarmDoneActions[15] = "com.dianxinos.clock.ALARM_DONE";
	}

	private static boolean isLockedAlarm = false;
	public final BroadcastReceiver mAlarmReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			LogUtil.d(TAG, "receive broadcast,action=" + action);
			if (action.endsWith("ALERT")) {
				if (LockScreenManager.getInstance(LockerService.this).isLocked()) {
					LockScreenManager.getInstance(LockerService.this).unLock(true);
					isLockedAlarm = true;
				}
			} else if (action.endsWith("DONE") || action.endsWith("killed")) {
				if (isLockedAlarm) {
					lock();
					isLockedAlarm = false;
				}
			}
		}
	};

	private void lock() {
		LockScreenManager.getInstance(LockerService.this).lock();
		sendObtainActiveNotificationMsg();
	}

	private void sendObtainActiveNotificationMsg() {
		Intent intent = new Intent();
		// intent.setAction(PandoraNotificationService.ACTION_OBTAIN_ACTIVE_NOTIFICATIONS);
		LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
	}

	private class SMSContentObserver extends ContentObserver {
		Context context;

		public SMSContentObserver(Context context, Handler handler) {
			super(handler);
			this.context = context;
		}

		private boolean checkPermission(Context context, String permission) {
			PackageManager pm = context.getPackageManager();
            return pm.checkPermission(permission, context.getPackageName()) == 0;
        }

		@Override
		public void onChange(boolean selfChange) {
			Uri uri = Uri.parse("content://sms/inbox");
			String[] projection = new String[] { "_id", "address", "date", "read", "type" };

			Cursor cur = null;
			try {
				if (checkPermission(context, permission.READ_SMS)) {
					cur = getContentResolver().query(uri, projection, "type = 1 and read = 0",
							null, "date desc"); // 获取手机内部短信
				}
			} catch (Exception ex) {
				ex.printStackTrace();
			}

			if (cur == null) {
				return;
			}
			int count = cur.getCount();
			long longDate = 0;
			String address = "";
			if (cur.moveToFirst()) { // 获取最近的一条短信内容
				int dateIndex = cur.getColumnIndex("date");
				longDate = cur.getLong(dateIndex);
				address = cur.getString(cur.getColumnIndex("address"));
			}
			if (LockScreenManager.getInstance(LockerService.this).isLocked()) {
				sendSmsReciveBroadcast(count, longDate, address); // 发送收到短信的广播
			}
			cur.close();
		}
	}

	private void sendSmsReciveBroadcast(int count, long date, String address) {
		Intent it = new Intent(TOOLBOX_RECIVE_SMS_ACTION);
		it.putExtra(SMS_WATCHER_UNREAD_COUNT, count);
		it.putExtra(SMS_WATCHER_DATE, date);
		it.putExtra(SMS_WATCHER_ADDRESS, address);
		sendBroadcast(it);
	}

}
